#!/usr/bin/python
# -*-coding:utf-8-*-
# pip install ddddocr 图片识别
"""江苏省危险废物监控系统"""
import asyncio
import os
from datetime import datetime
from time import sleep

import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from pyppeteer import launch

import common
import db

mysqldb = db.DbManager()

load_dotenv(verbose=True)
# 今天
today_time = common.TodayTime()
# 将-替换为.
today_time_new = today_time.replace('-', '.')
# 账号
username = os.getenv('LOGIN_ADMIN')
passworld = os.getenv('LOGIN_PWD')
url = os.getenv('URL')
username_1 = os.getenv('LOGIN_ADMIN_1')
passworld_1 = os.getenv('LOGIN_PWD_1')
url_1 = os.getenv('URL_1')

# 存储登录后cookie
new_cookies = ""


def event_alarm(cookie, now_time):
    import datetime
    now = datetime.datetime.now()
    this_month_start = datetime.datetime(now.year, now.month, 1).strftime('%Y-%m-%d')
    now_day = datetime.datetime.now().strftime('%Y-%m-%d')
    try:
        # 后台废气站点数量
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X -1_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
            'Accept': '*/*',
            'Host': '218.92.31.102:8400',
            'Origin': 'http://218.92.31.102:8400',
            'Referer': 'http://218.92.31.102:8400/WasteGas/RealTime/RealTimeDataQUIDYN/RealTimeData.aspx',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cookie': new_cookies
        }
        # 核与辐射作业
        payload = 'start='+this_month_start+'+00%3A00%3A00&end='+now_day+'+23%3A59%3A59&entName=&entCode=0&type=0&state=-1&isadmin=True&Method=GetReportsList&page=1&rows=500'
        resp = requests.post(
            "http://218.92.31.102:8400/ReDevelop/Ajax/XuWei/BasicInformation/Information/ReportsPlan.ashx",
            headers=headers, data=payload)
        print(resp)
        result = resp.json()  # 转化
        print(result['rows'])
        push_name_arr={1:"喷涂作业",2:"核与辐射作业",3:"火炬排放",4:"管道吹扫",99:"其他"}
        for i in range(len(result['rows'])):
            result['rows'][i]['C_REPORTS_DATE'] = datetime.datetime.strptime(result['rows'][i]['C_REPORTS_DATE'],
                                                                             '%Y-%m-%dT%H:%M:%S').strftime(
                '%Y-%m-%d %H:%M:%S')
            desc=result['rows'][i]['C_REPORTS_DATE'] + "_" + result['rows'][i]['C0070_ENTERPRISE_CODE'] + "_" +result['rows'][i]['C_REPORTS_GUID']
            # 检查是否存在数据 如果存在数据则跳过
            find_count = mysqldb.table_select_one(table="xw_event_alarm", where={"note":desc
                                                        })
            if find_count:
                continue
            info = {"type": result['rows'][i]['C_REPORTS_TYPE'],
                    "name": push_name_arr[result['rows'][i]['C_REPORTS_TYPE']],
                    "push_type":result['rows'][i]['C_REPORTS_TYPE'],
                    "push_name":push_name_arr[result['rows'][i]['C_REPORTS_TYPE']],
                    "push_time": result['rows'][i]['C_REPORTS_DATE'],
                    "note": desc,
                    'create_time': now_time,
                    }
            print(info)
            mysqldb.table_insert(table="xw_event_alarm", data=info)

        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X -1_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
            'Accept': '*/*',
            'Host': '218.92.31.102:8400',
            'Origin': 'http://218.92.31.102:8400',
            'Referer': 'http://218.92.31.102:8400/ReDevelop/Page/XuWei/WasteGas/RealTime/DataAlarmQUI/DataAlarm.aspx',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cookie': 'ASP.NET_SessionId=zgwvfw5ygq5hr00zcvjyrhhc;jeesite.session.id=b6ec3966230a4a689bd924781d260728'
        }
        payload = 'Method=QueryDataAlarm&start='+this_month_start+'+00%3A00%3A00&end='+now_day+'+23%3A59%3A59&city=0&subid=0&control=1%2C2%2C64%2C32%2C16%2C128&type=10&num=0.3&item=201%2C203%2C207%2C106%2C44&showValidate=0&page=1&rows=20'
        resp = requests.post(
            "http://218.92.31.102:8400/ReDevelop/ajax/XuWei/WasteGas/RealTime/DataAlarmQUI/DataAlarm.ashx",
            headers=headers, data=payload)
        result = resp.json()  # 转化
        for i in range(len(result['rows'])):
            result['rows'][i]['sDateTime'] = datetime.datetime.strptime(result['rows'][i]['sDateTime'],
                                                                        '%Y/%m/%d %H').strftime(
                '%Y-%m-%d %H:%M:%S')
            desc = result['rows'][i]['sDateTime'] + "_" + result['rows'][i]['sSubName'] + "_" + result['rows'][i][
                        'sItem']
            # 检查是否存在数据 如果存在数据则跳过
            find_count = mysqldb.table_select_one(table="xw_event_alarm", where={"note": desc
                                                                                 })
            if find_count:
                continue
            info = {"type": 5,
                    "name": "废气站点报警",
                    "push_type": 5,
                    "push_name": "废气站点报警",
                    "push_time": result['rows'][i]['sDateTime'],
                    "note":desc,
                    'create_time': now_time,
                    }
            mysqldb.table_insert(table="xw_event_alarm", data=info)

        # 废水数据报警
        payload = 'Method=QueryDataAlarm&start='+this_month_start+'+00%3A00%3A00&end='+now_day+'+23%3A59%3A59&city=0&subid=0&control=1%2C2%2C64%2C32%2C16%2C128&type=10&num=0.3&item=311%2C316&subtype=51&showValidate=0&page=1&rows=100'
        resp = requests.post(
            "http://218.92.31.102:8400/ReDevelop/ajax/XuWei/WasteWater/RealTime/DataAlarmQUI/DataAlarm.ashx",
            headers=headers, data=payload)
        print(resp)
        result = resp.json()  # 转化
        for i in range(len(result['rows'])):
            result['rows'][i]['sDateTime'] = datetime.datetime.strptime(result['rows'][i]['sDateTime'],
                                                                        '%Y/%m/%d %H').strftime(
                '%Y-%m-%d %H:%M:%S')
            desc = result['rows'][i]['sDateTime'] + "_" + result['rows'][i]['sSubName'] + "_" + result['rows'][i][
                        'sItem']
            # 检查是否存在数据 如果存在数据则跳过
            find_count = mysqldb.table_select_one(table="xw_event_alarm", where={"note": desc
                                                                                 })
            if find_count:
                continue
            info = {
                    "type": 6,
                    "name": "废水站点报警",
                    "push_type": 6,
                    "push_name": "废水站点报警",
                    "push_time": result['rows'][i]['sDateTime'],
                    "note": result['rows'][i]['sDateTime'] + "_" + result['rows'][i]['sSubName'] + "_" + result['rows'][i][
                        'sItem'],
                    'create_time': now_time,
                    }
            mysqldb.table_insert(table="xw_event_alarm", data=info)
    except:
        pass


async def login_1():
    now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # 月初第一天
    now = datetime.now()
    # userDataDir:记录上网记录 是否已登录等。。 userDataDir='./userdata',
    browser = await launch(headless=True, userDataDir='./userdata', args=['--disable-infobars', '--no-sandbox'])
    # browser = await launch(headless=False, userDataDir='./userdata', args=['--disable-infobars', '--no-sandbox'])
    page = await browser.newPage()
    await page.setUserAgent(
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER")
    await page.setViewport(viewport={'width': 1536, 'height': 768})
    await page.evaluateOnNewDocument('() =>{ Object.defineProperties(navigator,'
                                     '{ webdriver:{ get: () => false } }) }')

    await asyncio.wait([
        page.goto(url_1),
        page.waitForNavigation({'timeout': 50000}),
    ])
    sleep(2)
    # 查看title 是否等于
    login_text = await page.querySelectorAllEval('#btnLogin', 'nodes=>nodes.map(node=>node.innerText)')
    print(str(login_text))
    print("到这边")
    if "登" in str(login_text[0]):
        print("点击登录")
        # 点击登录
        await page.type(
            '#username',
            username_1, {'delay': 120})
        await page.type(
            '#password',
            passworld_1, {'delay': 120})
        # 点击登录
        await page.click('#btnLogin')

    sleep(1)
    await asyncio.wait([
        page.goto('http://218.92.31.102:8400/ssologin.aspx?uid=admin&url=index.aspx'),
        page.waitForNavigation({'timeout': 100000}),
    ])
    sleep(1)
    # 存储cookie
    page_cookie = await page.cookies()
    print(page_cookie)
    cookies = ''
    for cookie in page_cookie:
        str_cookie = '{0}={1};'
        str_cookie = str_cookie.format(cookie.get('name'), cookie.get('value'))
        cookies += str_cookie
    new_cookies = cookies
    print(new_cookies)
    # 废气数据报警
    event_alarm(new_cookies, now_time)
    # 后台废气站点数量
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X -1_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
        'Accept': '*/*',
        'Host': '218.92.31.102:8400',
        'Origin': 'http://218.92.31.102:8400',
        'Referer': 'http://218.92.31.102:8400/WasteGas/RealTime/RealTimeDataQUIDYN/RealTimeData.aspx',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': new_cookies
    }
    payload = 'Method=QueryRealTimeData&levels=1%2C2%2C64%2C32&codes=201%2C203%2C207%2C44&city=0&showValidate=0&fault=0&subname=&entname=&subType=0&Subgarbage=false'
    resp = requests.post(
        "http://218.92.31.102:8400/ajax/WasteGas/RealTime/RealTimeDataQUIDYN/RealTimeData.ashx",
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    info = {"name": "废气监测站点数量",
            "num": result['total'],
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_station_num", data=info)
    # 废水站点数量
    payload = 'Method=QueryRealTimeData&levels=1%2C2%2C64%2C32&codes=316%2C311%2C313%2C466%2C302%2C301&city=0&subname='
    resp = requests.post(
        "http://218.92.31.102:8400/ajax/WasteWater/RealTime/RealTimeDataQUIDYN/RealTimeData.ashx",
        headers=headers, data=payload)
    result = resp.json()  # 转化
    info = {"name": "废水监测站点数量",
            "num": result['total'],
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_station_num", data=info)

    # 污水厂站点数量
    payload = 'Method=QueryRealTimeData&levels=1%2C2%2C64%2C32&codes=316%2C311%2C313%2C466%2C302%2C301&city=0&subname='
    resp = requests.post(
        "http://218.92.31.102:8400/ajax/SewagePlant/RealTime/RealTimeDataQUIDYN/RealTimeData.ashx",
        headers=headers, data=payload)
    result = resp.json()  # 转化
    info = {"name": "污水厂监测站点数量",
            "num": result['total'],
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_station_num", data=info)

    # 地表水站点数量
    payload = 'Method=QueryRealTimeData&codes=315%2C314%2C311%2C313%2C466%2C302%2C463%2C465%2C301&city=0&subname=&buoy=0'
    resp = requests.post(
        "http://218.92.31.102:8400/ajax/RiverSection/RealTime/RealTimeDataQUIDYN/RealTimeData.ashx",
        headers=headers, data=payload)
    result = resp.json()  # 转化
    info = {"name": "地表水监测站点数量",
            "num": result['total'],
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_station_num", data=info)

    # 水源地站点数量
    payload = 'Method=QueryRealTimeData&codes=314%2C311%2C313%2C466%2C302%2C315%2C463%2C465%2C301&city=0'
    resp = requests.post(
        "http://218.92.31.102:8400/ReDevelop/Ajax/XuWei/DrinkWater/RealTime/RealTimeDataQUIDYN/RealTimeData.ashx",
        headers=headers, data=payload)
    result = resp.json()  # 转化
    info = {"name": "水源监测站点数量",
            "num": result['total'],
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_station_num", data=info)

    # 水源地站点数量
    payload = 'Method=QueryRealTimeData&codes=314%2C311%2C313%2C466%2C302%2C315%2C463%2C465%2C301&city=0'
    resp = requests.post(
        "http://218.92.31.102:8400/ReDevelop/Ajax/XuWei/DrinkWater/RealTime/RealTimeDataQUIDYN/RealTimeData.ashx",
        headers=headers, data=payload)
    result = resp.json()  # 转化
    info = {"name": "水源监测站点数量",
            "num": result['total'],
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_station_num", data=info)

    # 城市空气站点数量
    payload = 'Method=QueryRealTimeData&city=0&levels=1%2C2%2C64%2C32&codes=2%2C132%2C107%2C108%2C10108%2C201%2C141%2C203%2C106%2C126%2C350%2C378%2C130%2C129%2C847&subname=&aqi_order=default&air_Type=-1'
    resp = requests.post(
        "http://218.92.31.102:8400/ajax/CityAir/RealTime/RealTimeDataQUIDYN/RealTimeData.ashx",
        headers=headers, data=payload)
    result = resp.json()  # 转化
    info = {"name": "城市空气监测站点数量",
            "num": result['total'],
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_station_num", data=info)

    # VOC站点数量
    payload = 'Method=QueryRealTimeData&city=0&levels=1%2C2%2C64%2C32&codes=201%2C203%2C207%2C44&showValidate=0&fault=0&subname=&Subgarbage=undefined'
    resp = requests.post(
        "http://218.92.31.102:8400/ajax/VOC/RealTime/RealTimeDataCommon/RealTimeData.ashx",
        headers=headers, data=payload)
    result = resp.json()  # 转化
    info = {"name": "VOC监测站点数量",
            "num": result['total'],
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_station_num", data=info)
    # 站点分析结束
    await asyncio.wait([
        page.goto('http://218.92.31.102:8423/a/iphb/bigscreen/tofaoindexshj'),
        page.waitForNavigation({'timeout': 50000}),
    ])
    await asyncio.wait([
        page.goto('http://218.92.31.102:8423/a/iphb/bigscreen/tofaoindexshj'),
        page.waitForNavigation({'timeout': 100000}),
    ])
    sleep(10)
    content = await page.content()
    soup = BeautifulSoup(content, "html.parser")
    print(soup)
    # COD超标
    codCbCount = soup.find('span', id="codCbCount").text
    info = {"name": "COD超标",
            "num": codCbCount,
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_water_station_num", data=info)
    # 总磷超标
    tpCbCount = soup.find('span', id="tpCbCount").text
    info = {"name": "总磷超标",
            "num": tpCbCount,
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_water_station_num", data=info)
    # 总氮超标
    tnCbCount = soup.find('span', id="tnCbCount").text
    info = {"name": "总氮超标",
            "num": tnCbCount,
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_water_station_num", data=info)
    # 氨氮超标
    nh2nCbCount = soup.find('span', id="nh2nCbCount").text
    info = {"name": "氨氮超标",
            "num": nh2nCbCount,
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_water_station_num", data=info)
    # waterStationCount
    waterStationCount = soup.find('span', id="waterStationCount").text
    print(waterStationCount)
    info = {"name": "地表水站点",
            "num": waterStationCount,
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_water_station_num", data=info)
    # 地表水站点:
    stationCount = soup.find('span', id="stationCount").text
    print(stationCount)
    info = {"name": "废水站点",
            "num": stationCount,
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_water_station_num", data=info)
    if int(stationCount) == 0:
        # 为0的话 则调用接口去获取数据
        headers = {
            'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)',
            'Accept': '*/*',
            'Host': '180.101.234.11:20002',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded'
        }

        # 空气质量同期分析 开始
        payload = {}
        resp = requests.get(
            "http://218.92.31.102:8421/datasupport/online/surfacewater/findFSStationStatisticsList",
            headers=headers, data=payload)
        result = resp.json()  # 转化
        print(result['data'])
        for i in range(len(result['data'])):
            if result['data'][i]['name'] == "超标站点":
                result['data'][i]['name'] = "COD超标"
            info = {"name": result['data'][i]['name'],
                    "num": result['data'][i]['countval'],
                    'create_time': now_time,
                    }
            mysqldb.table_insert(table="xw_water_station_num", data=info)

    await asyncio.wait([
        page.goto('http://218.92.31.102:8423/a/iphb/bigscreen/tofaoindexdq'),
        page.waitForNavigation({'timeout': 50000}),
    ])
    await asyncio.wait([
        page.goto('http://218.92.31.102:8423/a/iphb/bigscreen/tofaoindexdq'),
        page.waitForNavigation({'timeout': 100000}),
    ])
    sleep(10)
    content = await page.content()
    # 关闭
    await page.close()
    await browser.close()
    soup = BeautifulSoup(content, "html.parser")
    qytj = soup.find("td", id="qytj").text
    zdtj = soup.find("td", id="zdtj").text
    tctj = soup.find("td", id="tctj").text
    cbtj = soup.find("td", id="cbtj").text
    # VOC
    vocqytj = soup.find("td", id="vocqytj").text
    voczdtj = soup.find("td", id="voczdtj").text
    voctctj = soup.find("td", id="voctctj").text
    voccbtj = soup.find("td", id="voccbtj").text
    info = {"fqqy": qytj,
            "fqzd": zdtj,
            "fqtc": tctj,
            'fqcb': cbtj,
            'vocqy': vocqytj,
            'voczd': voczdtj,
            'voctc': voctctj,
            'voccb': voccbtj,
            'create_time': now_time,
            }
    mysqldb.table_insert(table="xw_site_num", data=info)


def xw_data():
    import datetime
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    now = datetime.datetime.now()
    # 40小时前 xw_water_station使用
    station_start = (now + datetime.timedelta(hours=-40)).strftime("%Y%m%d%H%M")  # 获取前一小时
    station_end = datetime.datetime.now().strftime('%Y%m%d%H%M')
    # 月初第一天
    this_month_start = datetime.datetime(now.year, now.month, 1).strftime('%Y-%m-%d')
    now_day = datetime.datetime.now().strftime('%Y-%m-%d')
    # 获取最新一条上报数据
    spider_news_count = mysqldb.table_select_one(table="xw_event_report", where="1=1", order="dateTime", sort="desc")
    # 报警分析
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X -1_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
        'Accept': '*/*',
        'Host': '218.92.31.102:8400',
        'Origin': 'http://218.92.31.102:8400',
        'Referer': 'http://218.92.31.102:8400/Utility/EventReportAdmin/EventReportAdminList.aspx',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded',
        # 'Cookie':'ASP.NET_SessionId=m3fsofhactgfcemrk3db2fct; jeesite.session.id=588cde595174490894647ebb18c47dd1; JSESSIONID=4731BEF2FCA89FAE16876E655DBCB0D5',
    }
    station_start_str = (now + datetime.timedelta(hours=-50)).strftime("%Y-%m-%d")  # 获取前一小时
    station_end_str = datetime.datetime.now().strftime('%Y-%m-%d')
    payload = 'Method=DoQueryList&dateStart=' + station_start_str + '%2000%3A00&dateEnd=' + station_end_str + '%2023%3A59&city=0'
    resp = requests.post(
        "http://218.92.31.102:8400/ajax/Utility/EventReportAdminList.ashx",
        headers=headers, data=payload)
    result = resp.json()  # 转化
    # 获取最新一条上报时间
    for i in range(len(result)):
        info = {"cityName": result[i]['cityName'],
                "pname": result[i]['pname'],
                "detail": result[i]['detail'],
                "startTime": result[i]['startTime'],
                "endTime": result[i]['endTime'],
                "dateTime": result[i]['dateTime'],
                'create_time': now_time}
        if spider_news_count == None:
            mysqldb.table_insert(table="xw_event_report", data=info)
            continue
        result[i]['dateTime'] = datetime.datetime.strptime(result[i]['dateTime'], '%Y/%m/%d %H:%M:%S').strftime(
            '%Y-%m-%d %H:%M:%S')
        if str(spider_news_count['dateTime']) <= result[i]['dateTime']:
            # 如果是同一时间上报 则 检查是否存在数据
            find_info = mysqldb.table_select_one(table="xw_event_report", field="id",
                                                 where={"cityName": result[i]['cityName'], "pname": result[i]['pname'],
                                                        "detail": result[i]['detail']})
            # 存在数据则跳过
            if find_info:
                info['update_time'] = now_time
                mysqldb.table_update(table="xw_event_report", data=info,
                                     where={"id": find_info['id']})
            else:
                mysqldb.table_insert(table="xw_event_report", data=info)

    headers = {
        'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)',
        'Accept': '*/*',
        'Host': '180.101.234.11:20002',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    # 空气质量同期分析 开始
    payload = {}
    resp = requests.get(
        "http://218.92.31.102:8421/datasupport/online/airdata/queryAirDataByMonthTB",
        headers=headers, data=payload)
    result = resp.json()  # 转化
    for i in range(len(result['data'])):
        print(result['data'][i])
        info = {"dt": result['data'][i]['dt'],
                "pm25": result['data'][i]['pm25'],
                "pm25TB": result['data'][i]['pm25TB'],
                'create_time': now_time}
        mysqldb.table_insert(table="xw_air_month_data", data=info)
    # 空气质量同期分析 结束

    # 园区试试空气质量
    payload = {}
    resp = requests.get(
        "http://218.92.31.102:8421/datasupport/online/airdata/queryXWTodayAirData",
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    print(result)
    for i in range(len(result['data'])):
        if result['data'][i]['aqi'] >= '51' and result['data'][i]['aqi'] <= '100':
            str_2 = "良"
        elif result['data'][i]['aqi'] >= '101' and result['data'][i]['aqi'] <= '150':
            str_2 = "轻度污染"
        elif result['data'][i]['aqi'] >= '151' and result['data'][i]['aqi'] <= '200':
            str_2 = "中度污染"
        elif result['data'][i]['aqi'] >= '201' and result['data'][i]['aqi'] <= '300':
            str_2 = "重度污染"
        elif result['data'][i]['aqi'] >= '301' and result['data'][i]['aqi'] <= '500':
            str_2 = "严重污染"
        else:
            str_2 = "优"
        info = {"o3": result['data'][i]['o3'],
                "pm25TB": result['data'][i]['pm25TB'],
                "dt": result['data'][i]['dt'],
                "pm25": result['data'][i]['pm25'],
                "pm10": result['data'][i]['pm10'],
                "so2": result['data'][i]['so2'],
                "nox": result['data'][i]['nox'],
                "no2": result['data'][i]['no2'],
                "co": result['data'][i]['co'],
                "qy": result['data'][i]['qy'],
                "fs": result['data'][i]['fs'],
                "fx": result['data'][i]['fx'],
                "wd": result['data'][i]['wd'],
                "sd": result['data'][i]['sd'],
                "aqi": result['data'][i]['aqi'] + "," + str_2,
                'create_time': now_time}
        mysqldb.table_insert(table="xw_today_air", data=info)

    # 废气污染排放量统计开始
    payload = {}
    resp = requests.get(
        "http://218.92.31.102:8421/datasupport/online/getEntPFLByYear",
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    print(result)
    # SO2排放、NOx排放、颗粒物排放
    arr_so2 = []
    arr_NOx = []
    arr_keli = []
    for i in range(len(result['data'])):
        if result['data'][i]['c0001_item_code'] == "201":
            # SO2排放
            arr_so2.append(result['data'][i])
        elif result['data'][i]['c0001_item_code'] == "203":
            arr_NOx.append(result['data'][i])
        elif result['data'][i]['c0001_item_code'] == "207":
            arr_keli.append(result['data'][i])
    for i in range(len(arr_so2)):
        top = i + 1
        if top > 5:
            continue
        info = {"type": arr_so2[i]['c0001_item_code'],
                "type_name": "SO2",
                "top": top,
                "name": arr_so2[i]['c0070_enterprise_name'],
                "value": str(arr_so2[i]['sumpfl']) + "(t)批复量 ≤--",
                'create_time': now_time}
        mysqldb.table_insert(table="xw_emission_pollution", data=info)
    for i in range(len(arr_NOx)):
        top = i + 1
        if top > 5:
            continue
        info = {"type": arr_NOx[i]['c0001_item_code'],
                "type_name": "SO2",
                "top": top,
                "name": arr_NOx[i]['c0070_enterprise_name'],
                "value": str(arr_NOx[i]['sumpfl']) + "(t)批复量 ≤--",
                'create_time': now_time}
        mysqldb.table_insert(table="xw_emission_pollution", data=info)
    for i in range(len(arr_keli)):
        top = i + 1
        if top > 5:
            continue
        info = {"type": arr_keli[i]['c0001_item_code'],
                "type_name": "SO2",
                "top": top,
                "name": arr_keli[i]['c0070_enterprise_name'],
                "value": str(arr_keli[i]['sumpfl']) + "(t)批复量 ≤--",
                'create_time': now_time}
        mysqldb.table_insert(table="xw_emission_pollution", data=info)
    # 废气污染排放量统计结束

    # 地表水变化趋势 开始
    payload = {}
    resp = requests.get(
        "http://218.92.31.102:8421/datasupport/spatial/surfacewater/station/queryswitemhourcount?startTime=" + str(
            station_start) + "&endTime=" + str(station_end),
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    print(result)
    for i in range(len(result['data'])):
        print(result['data'][i])
        info = {"stationId": result['data'][i]['stationId'],
                "stationName": result['data'][i]['stationName'],
                "kms": result['data'][i]['kms'],
                "nh4s": result['data'][i]['nh4s'],
                "o2audits": result['data'][i]['o2audits'],
                "phs": result['data'][i]['phs'],
                "tns": result['data'][i]['tns'],
                "tps": result['data'][i]['tps'],
                "ntuaudits": result['data'][i]['ntuaudits'],
                "dateTimes": result['data'][i]['dateTimes'],
                'create_time': now_time}
        mysqldb.table_insert(table="xw_water_station", data=info)
    # 地表水变化趋势 结束

    # 园区污水厂污水排口实时监测 开始
    stationId = 14058
    payload = {}
    resp = requests.get(
        "http://218.92.31.102:8421/datasupport/online/surfacewater/findMonitoringDataList?stationId=" + str(stationId),
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    print(result)
    for i in range(len(result['data'])):
        print(result['data'][i])
        info = {"name": result['data'][i]['c0007_PNAME'],
                "item_desc": result['data'][i]['c0008_ITEM_DESC'],
                "item_value": result['data'][i]['c1705_VALUE'],
                "item_stdvalue": result['data'][i]['c0115_STDVALUE'],
                'create_time': now_time}
        mysqldb.table_insert(table="xw_water_monitoring", data=info)
    # 园区污水厂污水排口实时监测 结束


def xw_two():
    now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # 月初第一天
    now = datetime.now()
    this_month_start = datetime(now.year, now.month, 1).strftime('%Y-%m-%d')
    now_day = datetime.now().strftime('%Y-%m-%d')
    headers = {
        'Referer': 'http://180.101.234.11:20002/bigdata/login/viewRunner.html?viewId=http://180.101.234.11:20002/bigdata/home.js&viewParams=%7B%7D',
        'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)',
        'Accept': '*/*',
        'Host': '180.101.234.11:20002',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    # 产废类型TOP5
    payload = 'resVer=1&certCode=sc-res-18888888888&resCode=B_CF_QTY_BY_WasteType&jsonParam=%7B%22startDate%22%3A%22' + this_month_start + '%2000%3A00%3A00%22%2C%22endDate%22%3A%22' + now_day + '%2023%3A59%3A59%22%2C%22top%22%3A%225%22%2C%22areaCode%22%3A%22320773%22%7D'
    resp = requests.post(
        "http://180.101.234.11:20002/dateCenter/system/resource/listByDynamicParam",
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    print(result['data'])
    total = 0
    for i in range(len(result['data'])):
        total += result['data'][i]['prodQuant']
    print(total)
    # 添加到表
    for i in range(len(result['data'])):
        info = {"code": result['data'][i]['code'],
                "top": i + 1,
                "prod_quant": result['data'][i]['prodQuant'],
                "ratio": round(result['data'][i]['prodQuant'] / total, 2),
                }
        now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        info['create_time'] = now_time
        mysqldb.table_insert(table="waste_type", data=info)
    # 产废量
    payload = 'resVer=1&certCode=sc-res-18888888888&resCode=B_cf_quantity&jsonParam=%7B%22startDate%22%3A%22' + this_month_start + '%22%2C%22endDate%22%3A%22' + now_day + '%22%2C%22areaCode%22%3A%22320773%22%7D'
    resp = requests.post(
        "http://180.101.234.11:20002/dateCenter/system/resource/listByDynamicParam",
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    print(result)
    # 添加到表
    total_qty = 0
    for i in range(len(result['data'])):
        info = {"code": result['data'][i]['code'],
                "qty": result['data'][i]['qty'],
                "type": result['data'][i]['type'],
                }
        total_qty += result['data'][i]['qty']
        info['create_time'] = now_time
        mysqldb.table_insert(table="waste_quantity_toal", data=info)
    info = {"code": "total",
            "qty": total_qty,
            "type": "本月产废量",
            }
    mysqldb.table_insert(table="waste_quantity_toal", data=info)

    # 贮存量
    payload = 'resVer=1&certCode=sc-res-18888888888&resCode=B_storage_qty_total&jsonParam=%7B%22area_code%22%3A%22320773%22%2C%22nowTime%22%3A%22' + now_day + '%22%7D'
    resp = requests.post(
        "http://180.101.234.11:20002/dateCenter/system/resource/listByDynamicParam",
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    print(result)
    day_arr = {"now": "当前贮存量", "over90": "超90天贮存量", "over180": "超180天贮存量", "overOneYear": "超一年贮存量"}
    for i in range(len(result['data'])):
        if result['data'][i]['qty']:
            pass
        else:
            result['data'][i]['qty'] = 0
        info = {"code": "", "qty": result['data'][i]['qty'], "type": day_arr[result['data'][i]['type']],
                'create_time': now_time}
        mysqldb.table_insert(table="waste_quantity_toal", data=info)

    # 危废转移
    payload = 'resVer=1&certCode=sc-res-18888888888&resCode=B_TranCountByArea&jsonParam=%7B%22areaCode%22%3A%22320773%22%2C%22code%22%3A%22320773%22%2C%22level%22%3A3%2C%22startDate%22%3A%2' + this_month_start + '%2000%3A00%3A00%22%2C%22endDate%22%3A%22' + now_day + '%2023%3A59%3A59%22%7D'
    resp = requests.post(
        "http://180.101.234.11:20002/dateCenter/system/resource/listByDynamicParam",
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    print(result)
    for i in range(len(result['data'])):
        info = {"name": result['data'][i]['name'], "rece_qty": result['data'][i]['receQuantity'],
                "tran_qty": result['data'][i]['tranQuantity'],
                'now_time': now_day, "lat": result['data'][i]['lat'], "lon": result['data'][i]['lon'],
                'create_time': now_time}
        mysqldb.table_insert(table="waste_tran", data=info)

    # 利用处置方式占比
    payload = 'resVer=1&certCode=sc-res-18888888888&resCode=B_disposalType_pro&jsonParam=%7B%22areaCode%22%3A%22320773%22%2C%22startDate%22%3A%22' + this_month_start + '%2000%3A00%3A00%22%2C%22endDate%22%3A%22' + now_day + '%2023%3A59%3A59%22%7D'
    resp = requests.post(
        "http://180.101.234.11:20002/dateCenter/system/resource/listByDynamicParam",
        headers=headers, data=payload)
    print(resp)
    result = resp.json()  # 转化
    total = 0
    for i in range(len(result['data'])):
        total += result['data'][i]['qty']
    print(total)
    for i in range(len(result['data'])):
        if result['data'][i]['qty']:
            ratio = round(result['data'][i]['qty'] / total, 4)
        else:
            ratio = 0
        info = {"type": result['data'][i]['DisposalType'], "qty": result['data'][i]['qty'],
                "ratio": ratio,
                "remark": result['data'][i]['remark'],
                'create_time': now_time}
        mysqldb.table_insert(table="disposal_type", data=info)


class Egas:
    def __init__(self):
        self.url = url
        self.main()

    def main(self):
        # 登录获取
        asyncio.get_event_loop().run_until_complete(login_1())
        # 运营中心大屏
        xw_data()
        xw_two()

Egas()
